package com.msh.starter.captcha.bean;

import com.msh.frame.client.exception.ServiceException;
import com.msh.starter.captcha.util.CaptchaUtil;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class StaticImageCaptcha extends AbstractCaptcha{


  public StaticImageCaptcha(Font font, int width, int height) {
    super(font, width, height);
  }

  @Override
  public void outputStream(String text, OutputStream os) {
    int length = text.length();
    Color[] colors = CaptchaUtil.colors(length);
    BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
    Graphics2D g = (Graphics2D)img.getGraphics();
    g.setBackground(Color.WHITE);
    g.fillRect(0,0,width,height);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
    drawLine(g);
    drawOval(g);
    drawBezierLine(g);
    g.setFont(font);
    FontMetrics fontMetrics = g.getFontMetrics();
    int averageWidth = width/length;
    for(int i=0;i<length;i++){
      g.setColor(colors[i]);
      char c = text.charAt(i);
      Rectangle2D rectangle2D = fontMetrics.getStringBounds(String.valueOf(c), g);
      g.drawString(String.valueOf(c),getDrawStringX(rectangle2D, averageWidth, i), getDrawStringY(rectangle2D));
    }
    g.dispose();
    try {
      ImageIO.write(img,"png",os);
    } catch (IOException e) {
      log.error("图片输出失败",e );
      ServiceException.doThrow("图片输出失败");
    }
  }
}
